<template>
  <div class="course-card">
    <div class="card">
      <div class="card-header bg-primary text-white p-3">
        <h3 class="m-0">{{ course.course_name }}</h3>
      </div>
      <div class="card-body p-3">
        <p class="mb-2"><strong>课程编号：</strong> {{ course.course_id }}</p>
        <p class="mb-2"><strong>描述：</strong> {{ course.description || '暂无描述' }}</p>
        <p class="mb-2"><strong>学分：</strong> {{ course.credit_hours }}</p>
        <p class="mb-2"><strong>平时成绩占比：</strong> {{ (course.daily_weight * 100).toFixed(0) }}%</p>
        <p class="mb-2"><strong>授课教师：</strong> {{ teacherNameProp || '未指定' }}</p>
        <p class="mb-2"><strong>教师ID：</strong> {{ course.teacher_id || '无' }}</p>
        <div class="mt-3 flex justify-content-between">
          <div>
            <Button label="详情" icon="pi pi-info-circle" class="p-button-info detail-button mr-2" @click="showDetails" />
            <Button label="删除" icon="pi pi-trash" class="p-button-danger delete-button" @click="confirmDelete" />
          </div>
          <router-link :to="`/courses/edit/${course.course_id}`">
            <Button label="编辑" icon="pi pi-pencil" class="p-button-primary edit-button" />
          </router-link>
        </div>
      </div>
    </div>
    
    <!-- 详情对话框 -->
    <Dialog 
      v-model:visible="detailsVisible" 
      :header="course.course_name + ' 详细信息'" 
      :modal="true" 
      :style="{width: '650px'}" 
      :dismissableMask="true"
      class="course-details-dialog">
      <div class="course-details p-4">
        <div class="grid">
          <div class="col-12 md:col-6 mb-3">
            <div class="flex flex-column">
              <span class="text-lg font-bold mb-2">基本信息</span>
              <div class="field-row">
                <span class="field-label">课程ID：</span>
                <span class="field-value">{{ course.course_id }}</span>
              </div>
              <div class="field-row">
                <span class="field-label">课程名称：</span>
                <span class="field-value">{{ course.course_name }}</span>
              </div>
              <div class="field-row">
                <span class="field-label">课程编码：</span>
                <span class="field-value">{{ course.course_number }}</span>
              </div>
              <div class="field-row">
                <span class="field-label">授课教师：</span>
                <span class="field-value">{{ teacherNameProp || '未指定' }}</span>
              </div>
              <div class="field-row">
                <span class="field-label">学分：</span>
                <span class="field-value">{{ course.credit_hours }}</span>
              </div>
              <div class="field-row">
                <span class="field-label">状态：</span>
                <span class="field-value">{{ formatStatus(course.status) }}</span>
              </div>
            </div>
          </div>
          
          <div class="col-12 md:col-6 mb-3">
            <div class="flex flex-column">
              <span class="text-lg font-bold mb-2">时间与成绩</span>
              <div class="field-row">
                <span class="field-label">开始日期：</span>
                <span class="field-value">{{ formatDate(course.start_date) }}</span>
              </div>
              <div class="field-row">
                <span class="field-label">结束日期：</span>
                <span class="field-value">{{ formatDate(course.end_date) }}</span>
              </div>
              <div class="field-row">
                <span class="field-label">平时成绩占比：</span>
                <span class="field-value">{{ (course.daily_weight * 100).toFixed(0) }}%</span>
              </div>
              <div class="field-row">
                <span class="field-label">考试成绩占比：</span>
                <span class="field-value">{{ (course.exam_weight * 100).toFixed(0) }}%</span>
              </div>
              <div class="field-row">
                <span class="field-label">作业成绩占比：</span>
                <span class="field-value">{{ (course.homework_weight * 100).toFixed(0) }}%</span>
              </div>
            </div>
          </div>
          
          <div class="col-12">
            <div class="flex flex-column">
              <span class="text-lg font-bold mb-2">课程描述</span>
              <div class="p-3 bg-gray-100 border-round">
                {{ course.description || '暂无课程描述' }}
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <Button label="关闭" icon="pi pi-times" @click="closeDetails" class="p-button-text" />
      </template>
    </Dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import Button from 'primevue/button';
import Dialog from 'primevue/dialog';
import { ApiService } from 'src/services/api';
import { useConfirm } from 'primevue/useconfirm';
import { useToast } from 'primevue/usetoast';

const confirm = useConfirm();
const toast = useToast();

const props = defineProps({
  course: {
    type: Object,
    required: true
  },
  teacherName: {
    type: String,
    default: ''
  }
});

const emit = defineEmits(['course-deleted']);

// 使用从父组件传递的教师名称
const teacherNameProp = props.teacherName;

// 控制详情对话框的显示状态
const detailsVisible = ref(false);

// 显示详情对话框
const showDetails = () => {
  console.log("显示详情对话框");
  detailsVisible.value = true;
};

// 关闭详情对话框
const closeDetails = () => {
  detailsVisible.value = false;
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未设置';
  
  try {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
  } catch (error) {
    return dateString;
  }
};

// 格式化状态
const formatStatus = (status) => {
  const statusMap = {
    'active': '活跃',
    'inactive': '暂停',
    'planned': '计划中'
  };
  
  return statusMap[status] || status;
};

// 显示删除确认对话框
const confirmDelete = () => {
  confirm.require({
    message: `确定要删除课程"${props.course.course_name}"吗？`,
    header: '删除确认',
    icon: 'pi pi-exclamation-triangle',
    acceptClass: 'p-button-danger',
    accept: () => {
      deleteCourse();
    },
    reject: () => {
      // 用户取消删除，不执行操作
    }
  });
};

// 执行删除操作
const deleteCourse = async () => {
  try {
    // 调用删除API
    await ApiService.get(`courses/delete/${props.course.course_id}`);
    
    // 删除成功后立即通知父组件更新
    emit('course-deleted', props.course.course_id);
    
    // 短暂延迟后刷新页面
    setTimeout(() => {
      window.location.reload();
    }, 1000);
  } catch (error) {
    console.error('删除课程失败:', error);
    
    // 显示错误消息
    toast.add({
      severity: 'error', 
      summary: '删除失败', 
      detail: `无法删除课程: ${error.message || '未知错误'}`,
      life: 5000
    });
  }
};

// 组件挂载时记录信息
onMounted(() => {
  console.log(`课程卡片挂载 - 课程: ${props.course.course_name}, 教师: ${teacherNameProp}`);
});
</script>

<style scoped>
.course-card {
  width: 100%;
  max-width: 350px;
  margin: 10px;
}

.card {
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e0e0e0;
  height: 100%;
}

.card:hover {
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
  transform: translateY(-2px);
}

.card-header {
  background-color: #2196F3;
}

.edit-button, .detail-button {
  border-radius: 20px;
  padding: 0.5rem 1rem;
  font-size: 0.875rem;
}

.field-row {
  margin-bottom: 8px;
  display: flex;
}

.field-label {
  font-weight: bold;
  min-width: 120px;
  color: #555;
}

.field-value {
  flex-grow: 1;
}

.course-details {
  max-height: 70vh;
  overflow-y: auto;
}

:deep(.course-details-dialog .p-dialog-header) {
  background-color: #2196F3;
  color: white;
}
</style> 